package com.example.mark.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mark.common.Result;
import com.example.mark.entity.Chat;
import com.example.mark.entity.User;
import com.example.mark.entity.UserFriendList;
import com.example.mark.entity.UserData;
import com.example.mark.mapper.UserFriendListMapper;
import com.example.mark.service.ChatService;
import com.example.mark.util.WebSocketService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


@RestController
public class ChatController {

    @Autowired
    private ChatService chatService;

    @Autowired
    private UserFriendListMapper userFriendListMapper;

    @PostMapping("/push")
    public ResponseEntity<String> pushToWeb(@RequestBody Chat chat) throws IOException {
        chat.setCreateTime(LocalDateTime.now());
        chatService.save(chat);
        WebSocketService.sendInfo(chat);


        return ResponseEntity.ok("MSG SEND SUCCESS");
    }

    @GetMapping("/close")
    public String close(String userId) {
        WebSocketService.close(userId);
        return "ok";
    }


    @GetMapping("/getOnlineUser")
    public Map getOnlineUser() {
        return WebSocketService.getOnlineUser();
    }


    @GetMapping("/getMessage")
    public ResponseEntity<List<Chat>> getMessage(String userId) {
        QueryWrapper<Chat> queryWrapper = new QueryWrapper();
        List<Chat> list = chatService.
                list(queryWrapper.lambda().eq(Chat::getTargetUserId, userId).or().eq(Chat::getUserId, userId));
        return ResponseEntity.ok(list);
    }


    @ApiOperation("1.0.1测试GET请求")
    @GetMapping("hello")
    public String getHello() {
        return "Hello World";
    }

    @PostMapping("/FriendList")
    public Result updateFriendList(@RequestBody Map<String,Object> requestParams){
        int userId = (int) requestParams.get("userId");
        int userFriendID = (int) requestParams.get("userFriendID");
        
        // 查询当前用户的好友列表记录
        QueryWrapper<UserFriendList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserFriendList friendListRecord = userFriendListMapper.selectOne(queryWrapper);
        
        if (friendListRecord == null) {
            // 如果不存在记录，创建新记录
            UserFriendList newRecord = new UserFriendList();
            newRecord.setUserId(userId);
            newRecord.setFriendList(String.valueOf(userFriendID));
            userFriendListMapper.insert(newRecord);
            return Result.success("添加成功");
        }
        
        String currentList = friendListRecord.getFriendList();
        if (currentList == null || currentList.isEmpty()) {
            currentList = String.valueOf(userFriendID);
        } else {
            // 计算当前列表中逗号的数量
            long commaCount = currentList.chars().filter(ch -> ch == ',').count();
            
            if (commaCount >= 19) {
                // 如果逗号数量超过19，移除第一个ID
                int firstCommaIndex = currentList.indexOf(',');
                String truncatedList = currentList.substring(firstCommaIndex + 1);
                currentList = truncatedList + "," + userFriendID;
            } else {
                // 如果逗号数量未超过19，直接添加新ID
                currentList = currentList + "," + userFriendID;
            }
        }
        
        // 更新记录
        friendListRecord.setFriendList(currentList);
        userFriendListMapper.updateById(friendListRecord);
        
        return Result.success("添加成功");
    }

    @GetMapping("/getFriendList")
    public Result getFriendList(@RequestBody Map<String,Object> requestParams) {
        int userId = (int) requestParams.get("userId");

        QueryWrapper<UserFriendList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserFriendList friendListRecord = userFriendListMapper.selectOne(queryWrapper);
        
        if (friendListRecord == null || friendListRecord.getFriendList() == null) {
            return Result.success(null);
        }

        String[] friendIds = friendListRecord.getFriendList().split(",");
        List<UserData> userDataList = userFriendListMapper.selectUserDataByIds(friendIds);

        return Result.success(userDataList);
    }
}
